//
//  ZWHSearchViewController.swift
//  约麻
//
//  Created by Syrena on 2017/7/20.
//  Copyright © 2017年 Sweet. All rights reserved.
//

import UIKit
import AVOSCloud
import Hyphenate
import MBProgressHUD

class ZWHSearchViewController: UIViewController {

    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var accountT: UITextField!
    
    var dataArray=[AVUser]()
    override func viewDidLoad() {
        super.viewDidLoad()
        setnavigation()
        tableview.register(UINib.init(nibName: "ZWHSearchTableViewCell", bundle: nil), forCellReuseIdentifier: "ZWHSearchTableViewCell")
    }

    //设置导航栏
    func setnavigation(){
        title = "找麻友"
        navigationController?.navigationBar.barTintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        //定义标题颜色与字体大小字典
        let dict:NSDictionary = [NSForegroundColorAttributeName: #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1),NSFontAttributeName : UIFont.boldSystemFont(ofSize: 13)]
        //标题设置颜色与字体大小
        
        navigationController?.navigationBar.titleTextAttributes = dict as? [String : AnyObject]
        
        let Btn = UIButton(frame: CGRect(x: 0, y: 0, width: 15, height: 15))
        Btn.setImage(UIImage.init(named:"黑色返回"), for: .normal)
        Btn.addTarget(self, action: #selector(backClicked), for: .touchUpInside)
        let back = UIBarButtonItem(customView: Btn)
        navigationItem.leftBarButtonItem = back
        
        
        
        
    }
    func backClicked(){
        navigationController?.popViewController(animated: true)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
    
    @IBAction func searchfriend(_ sender: UIButton) {
        let que = AVQuery(className: "_User")
        
        if accountT.text == AVUser.current()?.username{
            accountT.text = ""
            ZWHAlertController.showAlert(vc: self, title: "不能搜索自己哦", message: nil, style: .alert)
        }
        
        if accountT.text != ""{
            dataArray.removeAll()
            MBProgressHUD.showAdded(to: view, animated: true)
            que.whereKey("username", equalTo: accountT.text!)
            que.findObjectsInBackground({ [weak self](objects, error) in
                if error == nil{
                    if objects?.count != 0{
                        let user = objects?.last as? AVUser
                        self?.dataArray.append(user!)
                    }else{
                        ZWHAlertController.showAlert(vc: self!, title: "没有此麻友", message: nil, style: .alert)
                    }
                }else{
                    ZWHAlertController.showAlert(vc: self!, title: "查找失败", message: nil, style: .alert)
                }
                MBProgressHUD.hideAllHUDs(for: self?.view, animated: true)
                self?.tableview.reloadData()
            })
        }
    }
}
extension ZWHSearchViewController:UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "查找结果"
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableview.dequeueReusableCell(withIdentifier: "ZWHSearchTableViewCell", for: indexPath) as? ZWHSearchTableViewCell
        cell?.user = dataArray[indexPath.row]
        cell?.delegate = self
        return cell!
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        view.endEditing(true)
    }
    
}

extension ZWHSearchViewController:ZWHSearchTableViewCellDelegate{
    func requestfriend(username: String!) {
        let ac = UIAlertController(title: "约麻友", message: nil, preferredStyle: .alert)
        ac.addTextField { (textfield) in
            textfield.placeholder = "三缺一?"
        }
        
        let  sure = UIAlertAction(title: "申请", style: .default) { (action) in
            EMClient.shared().contactManager.addContact(username, message: ac.textFields?.last?.text, completion: { [weak self](abc, error) in
                if error == nil{
                    ZWHAlertController.showAlert(vc: self!, title: "约麻成功", message: nil, style: .alert)
                }else {
                    ZWHAlertController.showAlert(vc: self!, title: "约麻失败,重新再试", message: nil, style: .alert)
                }
            })
        }
        let cancel = UIAlertAction(title: "取消", style: .cancel) { (action) in
        }
        ac.addAction(sure)
        ac.addAction(cancel)
        
        present(ac, animated: true) { 
            
        }
        
    }
}
